#include "Player.h"

Player::Player()
{
	color = fl_rgb_color(204, 85, 0);
	radius = 50;
	moves = 0;
	name = "default";
	first_move = true;
}

Player::~Player()
{
}

bool Player::move()
{
	Board::get_instance()->wait_for_button();
	if(!first_move)
	{
		++moves;
	}
	return true;
}

int Player::get_total_moves()
{
	return moves;
}

string Player::get_name()
{
	return name;
}

void Player::set_name(string new_name)
{
	name = new_name;
}

bool Player::is_legal_move(pair<int, int> new_position)
{
	bool ret = true;
	if(new_position.first > 7 || new_position.first < 0)
	{
		ret = false;
	}

	if(new_position.second > 7 || new_position.second < 0)
	{
		ret = false;
	}

	if(ret == true && first_move == false)
	{
		if((position.first + 1 == new_position.first || position.first - 1 == new_position.first) &&
		   (position.second + 1 == new_position.second || position.second - 1 == new_position.second))
		{
			if(Board::is_occupied(make_pair(new_position.first, new_position.second)))
			{
				ret = false;
			}
			else
			{
				// All checks passed
				ret = true;
			}
		}
		else
		{
			ret = false;
		}
	}
	else if(ret == true && first_move == true)
	{
		if(new_position.first == 7)
		{
			// If any square in the bottom row
			ret = true;
			initialize(new_position);
			first_move = false;
		}
		else
		{
			ret = false;
		}
	}

	return ret;
}

void Player::initialize(pair<int,int> new_position)
{
	position = make_pair(new_position.first, new_position.second);
	Board::get_instance()->positions[position.first][position.second] = Board::Player_type::player;
	piece = new Circle(Point(position.second * 100 + radius, position.first * 100 + radius), radius / 2);
	piece->set_color(color);
	piece->set_style(Line_style(Line_style::solid, radius));
}

pair<int, int> Player::get_position()
{
	return position;
}

bool Player::has_legal_moves()
{
	bool ret = false;

	if(is_legal_move(make_pair(position.first - 1, position.second + 1)))
	{
		return true;
	}
	else if(is_legal_move(make_pair(position.first + 1, position.second + 1)))
	{
		return true;
	}
	else if(is_legal_move(make_pair(position.first - 1, position.second - 1)))
	{
		return true;
	}
	else if(is_legal_move(make_pair(position.first + 1, position.second - 1)))
	{
		return true;
	}

	return ret;
}

void Player::move_to_position(pair<int, int> new_position)
{
	Board::get_instance()->positions[position.first][position.second] = Board::Player_type::none;
	piece->move(100 * (new_position.second - position.second), 100 * (new_position.first - position.first));
	position = new_position;
	Board::get_instance()->positions[position.first][position.second] = Board::Player_type::player;
}